package com.example.interview.ch03;

/**
 * 静态同步synchronized方法
 *
 * @author anin
 * @date 2022/4/27 10:50 AM
 */
public class Test3 {

    /*
     * 使用synchronized对静态代码加锁，同一类里的其他加锁静态方法也会顺序执行
     * 普通加锁方法不受影响
     */

    public static void main(String[] args) {
        Test3ObjectService objectService = new Test3ObjectService();
        new Thread(()->{
            Test3ObjectService.methodA();
        }).start();
        new Thread(()->{
            Test3ObjectService.methodB();
        }).start();
        new Thread(()->{
            objectService.methodC();
        }).start();
    }
}


class Test3ObjectService {
    public synchronized static void methodA(){
        try {
            System.out.println("static methodA begin 线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
            Thread.sleep(3000);
            System.out.println("static methodA end   线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized static void methodB(){
        System.out.println("static methodB begin 线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
        System.out.println("static methodB end   线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
    }

    public synchronized void methodC(){
        System.out.println(" methodC begin 线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
        System.out.println(" methodC end   线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
    }
}